package com.ht.medicaltreatment.activity

import android.annotation.SuppressLint
import android.view.View
import androidx.activity.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.LogUtils
import com.gym.baselib.base.BaseActivity
import com.ht.medicaltreatment.R
import com.ht.medicaltreatment.adapter.BorrowDetailAdapter
import com.ht.medicaltreatment.bean.LoanSample
import com.ht.medicaltreatment.bean.rfidSampleBoxListData
import com.ht.medicaltreatment.utils.ScanUtils
import com.ht.medicaltreatment.utils.SoundUtils
import com.ht.medicaltreatment.view.TostDialog
import com.ht.medicaltreatment.viewmodel.BorrowBuildViewModel
import com.xgst.lib.utils.showToast
import kotlinx.android.synthetic.main.activity_borrow_detail_layout.*
import kotlinx.android.synthetic.main.activity_borrow_detail_layout.btnPositive
import kotlinx.android.synthetic.main.activity_borrow_detail_layout.recyclerView
import kotlinx.android.synthetic.main.activity_borrow_detail_layout.tvProjectName
import kotlinx.android.synthetic.main.activity_inventory.*
import kotlinx.android.synthetic.main.activity_return_record_layout.*

//借出订单详情
class BorrowOrderDetailActivity:BaseActivity(), View.OnClickListener {

    override fun getLayoutId() = R.layout.activity_borrow_detail_layout

    private var isOpen = false
    private val model by viewModels<BorrowBuildViewModel>()
    private val list = arrayListOf<LoanSample>()
    private var scanProgress = 0
    private var totalCount = 0

    private var orderId = -1
    private lateinit var adapter:BorrowDetailAdapter
    private var adapterList:MutableList<LoanSample>?=null
    private var boxList:MutableList<rfidSampleBoxListData>?=null

    @SuppressLint("ResourceAsColor")
    override fun init() {
        val isScan = intent.getIntExtra("isChecked",0)
        if(isScan == 0){
            ScanUtils.init {
                btnStart.setBackgroundColor(getColor(R.color.blue))
                btnStart.isEnabled = true
            }
        }else{
            btnPositive.visibility = View.GONE
        }
        btnStart.setOnClickListener(this)
        btnPositive.setOnClickListener(this)
        recyclerView.layoutManager = LinearLayoutManager(this)
        adapter = BorrowDetailAdapter(isScan)
        recyclerView.adapter = adapter
        showProgress()
        orderId = intent.getIntExtra("id",0)
        initData()
    }

    private fun initData() {
        model.detailBorrow(orderId,{
            dismissProgress()
            adapter.setNewInstance(it.loanSampleList)

            totalCount = it.loanSampleList.size
            scanProgress = it.loanSampleList.filter { it.status != 0 }.size
            tvScanProgress.text = "$scanProgress/$totalCount"
            setTitle(it.loanOrder.orderName)
            tvName.text = it.loanOrder.createUserName
            tvReturnTime.text = it.loanOrder.expectedReturnDate
            tvRemark.text = it.loanOrder.loanRemarks
            tvProjectName.text = it.loanOrder.projectName

            adapterList = it.loanSampleList

            it.loanSampleList.forEachIndexed { index, it ->
                it.position = index
                list += it
            }

            boxList = it.rfidSampleBoxList
        })
    }

    override fun onClick(v: View?) {
        when(v){
            btnStart -> {
                if(isOpen){
                    isOpen = false
                    btnStart.text = "开始盘点"
                    btnStart.setBackgroundColor(getColor(R.color.blue))
                    ScanUtils.close()
                }else{
                    btnStart.text = "停止盘点"
                    btnStart.setBackgroundColor(getColor(R.color.red))
                    isOpen = true
                    startScan()
                }
            }

            //确认借出
            btnPositive ->{
                if(scanProgress < totalCount){
                    showToast("请先完成盘点")
                    return
                }
                showProgress()
                model.jiechu(orderId){
                    dismissProgress()
                    ScanUtils.close()
                    finish()
                }
            }
        }
    }

    //开始盘点
    fun startScan(){
        ScanUtils.open { uid ->
            SoundUtils.playSound(SoundUtils.SOUND_SUCCESS)
            //过滤调样本盒标签的UID
            val result = boxList?.find { it.rfidCode == uid }
            if(result == null){
                val filterList = list.filterIndexed { index, loanSample ->
                    loanSample.rfidCode == uid
                }
                if(filterList == null || filterList.size == 0){
                    ScanUtils.close()
                    initData()
                    TostDialog(this).show("核验错误，请准备好之后，重新开始盘点")
                    isOpen = false
                    btnStart.text = "开始盘点"
                    btnStart.setBackgroundColor(getColor(R.color.blue))
                    scanProgress = 0
                    tvScanProgress.text = "$scanProgress/$totalCount"
                    return@open
                }else{
                    val bean = filterList[0]
                    adapter.data.get(bean.position).isChecked = true
                    adapter.notifyItemChanged(bean.position)
                    list.remove(bean)
                    scanProgress++
                    tvScanProgress.text = "$scanProgress/$totalCount"
                }
            }
           /*for (i in 0 until list.size){
                val bean = list[i]
                if(bean.rfidCode == it){
                    adapter.data.get(bean.position).isChecked = true
                    adapter.notifyItemChanged((bean.position))
                    list.remove(bean)
                    break
                }
            }*/
        }
    }
}
